package com.han.yrpc.core;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class SPIUtils {

    public static final String DEFAULT_HANDLER_MAPPINGS_LOCATION = "META-INF/yrpc.handlers";

    /**
     * @see org.springframework.beans.factory.xml.DefaultNamespaceHandlerResolver
     */
    public static Map<String, Object> getHandlerMappings() {
        Map<String, Object> handlerMappings;
        try {
            Properties mappings = PropertiesLoaderUtils.loadAllProperties(DEFAULT_HANDLER_MAPPINGS_LOCATION, null);
            if (log.isTraceEnabled()) {
                log.trace("Loaded NamespaceHandler mappings: " + mappings);
            }
            handlerMappings = new ConcurrentHashMap<>(mappings.size());
            CollectionUtils.mergePropertiesIntoMap(mappings, handlerMappings);
        } catch (IOException ex) {
            throw new IllegalStateException(
                    "Unable to load NamespaceHandler mappings from location [" + DEFAULT_HANDLER_MAPPINGS_LOCATION + "]", ex);
        }
        return handlerMappings;
    }
}
